// 数据库名称和版本
const DB_NAME = 'WebsiteRecommendationsDB';
const DB_VERSION = 1;
const WEBSITES_STORE = 'websites';

class IndexedDBService {
  constructor() {
    this.db = null;
  }

  // 打开数据库连接
  async openDB() {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(DB_NAME, DB_VERSION);

      request.onerror = () => {
        reject(new Error('无法打开数据库'));
      };

      request.onsuccess = (event) => {
        this.db = event.target.result;
        resolve(this.db);
      };

      // 创建对象存储空间
      request.onupgradeneeded = (event) => {
        this.db = event.target.result;
        
        // 创建网站存储空间
        if (!this.db.objectStoreNames.contains(WEBSITES_STORE)) {
          const objectStore = this.db.createObjectStore(WEBSITES_STORE, { keyPath: 'id' });
          objectStore.createIndex('name', 'name', { unique: false });
          objectStore.createIndex('category', 'category', { unique: false });
          objectStore.createIndex('createdAt', 'createdAt', { unique: false });
        }
      };
    });
  }

  // 添加网站
  async addWebsite(website) {
    if (!this.db) await this.openDB();
    
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([WEBSITES_STORE], 'readwrite');
      const objectStore = transaction.objectStore(WEBSITES_STORE);
      const request = objectStore.add(website);

      request.onsuccess = () => {
        resolve(request.result);
      };

      request.onerror = () => {
        reject(new Error('添加网站失败'));
      };
    });
  }

  // 获取所有网站
  async getAllWebsites() {
    if (!this.db) await this.openDB();
    
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([WEBSITES_STORE], 'readonly');
      const objectStore = transaction.objectStore(WEBSITES_STORE);
      const request = objectStore.getAll();

      request.onsuccess = () => {
        resolve(request.result);
      };

      request.onerror = () => {
        reject(new Error('获取网站列表失败'));
      };
    });
  }

  // 根据ID获取网站
  async getWebsiteById(id) {
    if (!this.db) await this.openDB();
    
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([WEBSITES_STORE], 'readonly');
      const objectStore = transaction.objectStore(WEBSITES_STORE);
      const request = objectStore.get(id);

      request.onsuccess = () => {
        resolve(request.result);
      };

      request.onerror = () => {
        reject(new Error('获取网站失败'));
      };
    });
  }

  // 更新网站
  async updateWebsite(website) {
    if (!this.db) await this.openDB();
    
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([WEBSITES_STORE], 'readwrite');
      const objectStore = transaction.objectStore(WEBSITES_STORE);
      const request = objectStore.put(website);

      request.onsuccess = () => {
        resolve(request.result);
      };

      request.onerror = () => {
        reject(new Error('更新网站失败'));
      };
    });
  }

  // 删除网站
  async deleteWebsite(id) {
    if (!this.db) await this.openDB();
    
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([WEBSITES_STORE], 'readwrite');
      const objectStore = transaction.objectStore(WEBSITES_STORE);
      const request = objectStore.delete(id);

      request.onsuccess = () => {
        resolve(request.result);
      };

      request.onerror = () => {
        reject(new Error('删除网站失败'));
      };
    });
  }

  // 获取所有分类
  async getCategories() {
    if (!this.db) await this.openDB();
    
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction([WEBSITES_STORE], 'readonly');
      const objectStore = transaction.objectStore(WEBSITES_STORE);
      const request = objectStore.getAll();

      request.onsuccess = () => {
        const websites = request.result;
        // 正确处理分类字段，兼容不同版本的数据
        const categories = [...new Set(websites.map(w => w.category).filter(Boolean))];
        resolve(categories);
      };

      request.onerror = () => {
        reject(new Error('获取分类失败'));
      };
    });
  }

  // 初始化示例数据
  async initializeSampleData() {
    const websites = await this.getAllWebsites();
    
    if (websites.length === 0) {
      // 读取所有JSON文件中的数据，排除RecommendWebData.json
      const jsonFiles = [
        'WallChange.json',
        'WallOver.json',
        'aiUse.json',
        'aicodeTalk.json',
        'see.json',
        'toolBox.json',
        '下载影视.json',
        '动漫.json',
        '影视在线.json',
        '游戏.json',
        '白嫖音乐.json',
        '老网站.json',
        '认知拓展.json'
      ];
      
      try {
        // 从各个JSON文件中加载数据
        for (const fileName of jsonFiles) {
          try {
            const response = await fetch(`/${fileName}`);
            const sampleWebsites = await response.json();
            
            // 添加所有网站数据
            for (const website of sampleWebsites) {
              // 检查是否已存在相同ID的网站
              const existingWebsite = await this.getWebsiteById(website.id);
              if (!existingWebsite) {
                // 转换字段名以匹配统一的数据结构
                const websiteToAdd = {
                  id: website.id,
                  name: website.name,
                  description: website.con,
                  category: website.lei,
                  url: website.linke,
                  createdAt: website.creatTime
                };
                await this.addWebsite(websiteToAdd);
              }
            }
          } catch (fileError) {
            console.warn(`加载文件 ${fileName} 失败:`, fileError);
          }
        }
      } catch (error) {
        console.error('加载示例数据失败:', error);
      }
    }
  }
}

export default new IndexedDBService();